package com.jiezhuo.handler;

import org.springframework.security.core.AuthenticationException;

import com.jiezhuo.utils.ExceptionUtil;
import com.jiezhuo.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.security.access.AccessDeniedException;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){

        log.error(ExceptionUtil.getMessage(e));
        return R.err().msg("未知异常");
    }
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public R rzException(RuntimeException e){
        log.error(ExceptionUtil.getMessage(e));
        return R.err().msg(e.getMessage()).code(4000);
    }

    @ExceptionHandler(RzException.class)
    @ResponseBody
    public R RzException(RzException e){
        log.error(ExceptionUtil.getMessage(e));
        return R.err().msg("添加失败").code(400);
    }
    @ExceptionHandler(value = AuthenticationException.class)
    public R handleException(AuthenticationException e) {
        //e.printStackTrace();
        String message = e.getMessage();
//        String msg=message.substring(message.indexOf("[")+1,message.indexOf("]"));
        //判断是角色错误还是权限错误

        return R.err().msg(message).code(401);
    }
    @ExceptionHandler(value = AccessDeniedException.class)
    public R handleAccessDeniedException(AccessDeniedException e) {
        //e.printStackTrace();

        //获取错误中中括号的内容
        String message = e.getMessage();
//        String msg=message.substring(message.indexOf("[")+1,message.indexOf("]"));
        return R.err().msg(message).code(401);
    }


}
